package com.tsystems.skilltest;

import javax.jms.JMSException;
import javax.xml.bind.JAXBException;

import com.tsystems.skilltest.processor.TransactionProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author aesipov
 */
public class ReceiveAndProcessTransactionService
{
    private static final Logger logger = LoggerFactory.getLogger(ReceiveAndProcessTransactionService.class);

    private TransactionReceiver  transactionReceiver;
    private TransactionProcessor transactionProcessor;

    public ReceiveAndProcessTransactionService(TransactionReceiver transactionReceiver, TransactionProcessor transactionProcessor) {
        this.transactionReceiver = transactionReceiver;
        this.transactionProcessor = transactionProcessor;
    }

    public void start()
    {
        try
        {
            transactionReceiver.init();
        }
        catch (JMSException e)
        {
            logger.error("TransactionReceiver initialization is failed", e);
        }
        while (true)
        {
            try
            {
                Transaction transaction = transactionReceiver.receive();
                logger.info("Transaction was recieved: {}", transaction);
                transactionProcessor.process(transaction);
            }
            catch (JMSException e)
            {
                logger.error("Recieve transaction is failed", e);
            }
            catch (JAXBException e)
            {
                logger.error("Recieve transaction is failed", e);
            }
        }
    }
}
